package com.open.chat.server.service;

import java.util.List;
import java.util.Objects;

import org.jim.core.ImChannelContext;
import org.jim.core.ImStatus;
import org.jim.core.config.ImConfig;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.AuthUserRespBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.core.protocol.IProtocol;
import org.jim.server.ImServerChannelContext;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.processor.login.AuthCmdProcessor;
import org.jim.server.protocol.AbstractProtocolCmdProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.open.chat.server.common.Common;
import com.open.chat.server.common.MsgCode;
import com.open.chat.server.utils.Https;

import cn.hutool.core.date.DateUtil;
@Component
public class AuthServiceProcessor extends AbstractProtocolCmdProcessor implements AuthCmdProcessor {
	private static Logger log = LoggerFactory.getLogger(AuthServiceProcessor.class);
	@Autowired
	private Https http;
	
	@Value("${lets.token.url}")
	private  String url;
	
	@Override
	public AuthUserRespBody doAuth(AuthReqBody loginReqBody, ImChannelContext imChannelContext) {
		//拿到协议
		ImServerChannelContext imServerChannelContext = (ImServerChannelContext)imChannelContext;
		IProtocol protocol = imServerChannelContext.getProtocolHandler().getProtocol();
		
		AuthUserRespBody respBody = new AuthUserRespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10009);
		//鉴权代码
		String token = loginReqBody.getToken();
		JSONObject js = new JSONObject();
		js.put("token", token);
		//JSONObject json = http.post(url, js,JSONObject.class);
		JSONObject json = new JSONObject();
		json.put("code", 200);
		JSONObject data1 = new JSONObject();
		data1.put("systemNumber", 10001);
		data1.put("name", "测试大大");
		json.put("data", data1);
		int code =  json.getInteger("code");
		//如果鉴权成功
		if(code == MsgCode.CODE_OK) {
			JSONObject data = json.getJSONObject("data");
			//同步最新用户信息
			User.Builder builder = 
						User.newBuilder()
						.userId(data.getString("systemNumber"))
						.nick(data.getString("name"))
						//.avatar(data.getString("headImg"))
						.terminal(Objects.isNull(protocol) ? Protocol.UNKNOWN : protocol.name())
						//额外参数拓展
//						.addExtra(Common.UserInfoExtKeys.id, data.getString("id"))
//						.addExtra(Common.UserInfoExtKeys.sex, data.getString("sex"))
//						.addExtra(Common.UserInfoExtKeys.email, data.getString("email"))
//						.addExtra(Common.UserInfoExtKeys.department, data.getString("dept"))
//						.addExtra(Common.UserInfoExtKeys.position, data.getString("job"))
//						.addExtra(Common.UserInfoExtKeys.policeType, data.getString("policeType"))
						;
			
			User user = builder.build();
			respBody.setUser(user);
			
			
		}else {
			respBody.setCode(ImStatus.C10010.getCode()).setMsg(ImStatus.C10010.getMsg());
			
		}
		return respBody;
	}


	@Override
	public void onSuccess(User user,ImChannelContext imChannelContext) {
		
		//绑定自己|更新自己的信息
		JimServerAPI.bindUser(imChannelContext, user);
		
		//绑定群组(绑定组会触发 @see RedisImStoreBindListener#onAfterGroupBind方法，
		//如果该组有该用户就无须绑定，否则维护缓存group.user；如果该用户有改组，无须绑定；否则维护缓存user.group
		ImServerConfig imServerConfig = ImConfig.Global.get();
		MessageHelper messageHelper = imServerConfig.getMessageHelper();
		List<String> groupIds  = messageHelper.getGroups(user.getUserId());
		if(groupIds != null) {
			for(String groupId : groupIds) {
				JimServerAPI.bindGroup(imChannelContext, groupId);
			}
		}
		
		log.info("当前用户:{}登录成功，登录时间：{}",imChannelContext.getUserId(),DateUtil.now());

	}

	@Override
	public void onFailed(ImChannelContext imChannelContext) {
		log.info("当前用户:{}登录失败，登录时间：{}",imChannelContext.getUserId(),DateUtil.now());
	}

	
}
